package com.ruoyi.system.monitortask.controller;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.monitortask.domain.MonitorTask;
import com.ruoyi.system.monitortask.domain.req.MonitorTaskReq;
import com.ruoyi.system.monitortask.service.IMonitorTaskService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 账号监控任务表(monitor_task)表控制层
 *
 * @author zyy
 * @date 2024-06-21 15:19:20
 */
@RestController
@RequestMapping("/monitorTask")
public class MonitorTaskController extends BaseController {
    /**
     * 服务对象
     */
    @Autowired
    private IMonitorTaskService monitorTaskService;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private ISysUserService userService;
    /**
     * 分页查询所有数据
     *
     * @param monitorTask 查询实体
     * @return 所有数据
     */
    @GetMapping("/list")
    public TableDataInfo list(MonitorTask monitorTask) {

        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<MonitorTask> queryWrapper = new LambdaQueryWrapper<>();
        if (!Objects.equals(userId, 1l)) {
            queryWrapper.eq(MonitorTask::getCreateId, userId);
        }
        queryWrapper.eq(StringUtils.isNotNull(monitorTask.getType()), MonitorTask::getType, monitorTask.getType());
        queryWrapper.eq(StringUtils.isNotNull(monitorTask.getIntervalDays()), MonitorTask::getIntervalDays,
                monitorTask.getIntervalDays());
        queryWrapper.eq(StringUtils.isNotNull(monitorTask.getState()), MonitorTask::getState,
                monitorTask.getState());
        queryWrapper.like(StringUtils.isNotEmpty(monitorTask.getName()), MonitorTask::getName, monitorTask.getName());
        queryWrapper.orderByDesc(MonitorTask::getId);
        if (!Objects.equals(monitorTask.getIsPage(), 2)) {
            startPage();
        }
        List<MonitorTask> list = monitorTaskService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)){
            List<Long> userIds = list.stream().map(s -> s.getCreateId()).collect(Collectors.toList());
            Long[] array = userIds.stream().toArray(Long[]::new);

            List<SysUser> users = userService.selectByIds(array);
            for (MonitorTask m : list) {
                for (SysUser sysUser : users) {
                    if (Objects.equals(m.getCreateId(),sysUser.getUserId())){
                        m.setCreateName(sysUser.getNickName());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(monitorTaskService.getMonitorTask(id));
    }

    /**
     * 新增数据
     *
     * @param monitorTask 实体对象
     * @return 新增结果
     */
    @Log(title = "MonitorTask", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult insert(@RequestBody MonitorTask monitorTask) {
        monitorTask.setCreateId(getUserId());
        monitorTask.setLastDate(DateUtils.parseDate("2024-01-01"));
        return toAjax(monitorTaskService.save(monitorTask));
    }

    /**
     * 修改数据
     *
     * @param monitorTask 实体对象
     * @return 修改结果
     */
    @Log(title = "MonitorTask", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult update(@RequestBody MonitorTask monitorTask) {
        monitorTask.setUpdateId(getUserId());
        return toAjax(monitorTaskService.updateById(monitorTask));
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @Log(title = "MonitorTask", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(monitorTaskService.deleteMonitorTaskAndMonitorTaskGoods(id));
    }

    @GetMapping("/pxye")
    public AjaxResult pxye() {
        String Key = "CY4nt0S6ihxR1kfcGp8gD7vPJoldO5Qr";
        String Secret = "apUbAqhxfHj72nOJ0vSPkldc6uC3Em1Y";

        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("px_monitor_config");
        if (CollectionUtils.isNotEmpty(sysDictDataList)) {
            for (SysDictData dictData : sysDictDataList) {
                if ("Key".equals(dictData.getDictLabel())) {
                    Key = dictData.getDictValue();
                }
                if ("Secret".equals(dictData.getDictLabel())) {
                    Secret = dictData.getDictValue();
                }
            }
        }
        String body = HttpRequest.post("http://c.p74.cn/api/account/balance")
                .form("apiKey", Key)
                .form("apiSecret", Secret).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(body);
        return AjaxResult.success(jsonObject);
    }


    @GetMapping("/statistics")
    public AjaxResult statistics(MonitorTaskReq req) {
        return AjaxResult.success(monitorTaskService.statistics(req));
    }

    @GetMapping("/allUser")
    public AjaxResult allUser() {
        return AjaxResult.success(monitorTaskService.allUser());
    }
}

